package org.edu.modules.enroll.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.enroll.entity.*;
import org.edu.modules.enroll.service.*;
import org.edu.modules.enroll.vo.ExportStuInfoVo;
import org.edu.modules.enroll.vo.VeZsRegistrationVo;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

/**
 * 新生信息查询
 * @author yhx
 */
@Api(tags="新生信息查询")
@RestController
@RequestMapping("enroll/stuInfoQuery")
public class StuInfoQueryController {

    @Resource
    private VeZsRegistrationService veZsRegistrationService;

    @Resource
    private VeDictYearsService veDictYearsService;

    @Resource
    private VeBaseBanjiService veBaseBanjiService;

    @Resource
    private IVeBaseManageService iVeBaseManageService;

    @Resource
    private VeBaseStudentService veBaseStudentService;
    @Resource
    private VeBaseGradeService veBaseGradeService;
    @Resource
    private VeBaseTeacherService veBaseTeacherService;

    @ApiOperation(value = "获取班级集合")
    @PostMapping(value = "/getClazz")
    public Result<?> getClazz(@ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId) {

        //条件构造器
        QueryWrapper<VeDictYears> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("curYear",1);
        VeDictYears one = veDictYearsService.getOne(queryWrapper);

        //获取当前年份
        String curYear = one.getCode();
//        ----------------(林彬辉)获取当前年份
//        Calendar date = Calendar.getInstance();
//        String year = String.valueOf(date.get(Calendar.YEAR));
//       -------------------
        QueryWrapper<VeBaseBanji> wrapper = new QueryWrapper<>();
        wrapper.eq("RXNF", curYear);
        wrapper.eq("specId", specialtyId);

        List<VeBaseBanji> list = veBaseBanjiService.list(wrapper);
//        ------------------------------林彬辉
//        BasicResponseBO<List<VeBaseBanji>> bSpecialtyId = iVeBaseManageService.getBanjiBySpecId(specialtyId);
//        List<VeBaseBanji> listBySpecialty = bSpecialtyId.getResult();
//        List<VeBaseBanji> list = new ArrayList<>();

//        //获取当前年份的班级
//        for (VeBaseBanji veBaseBanji : listBySpecialty){
//            if (veBaseBanji.getRxnf().equals(curYear)){
//                list.add(veBaseBanji);
//            }
//        }
        System.out.println(list+"当前年份的班级");
//        ---------------------------------
        return Result.OK(list);

    }

    @ApiOperation("获取新生信息集合")
    @PostMapping(value = "/select")
    public Result<?> getStuInfoList(@ApiParam("专业部ID") @RequestParam("facultyId")Long facultyId,
                                    @ApiParam("是否拥有学号") @RequestParam("isNum")Integer isNum,
                                    @ApiParam("专业ID") @RequestParam("specialtyId")Long specialtyId,
                                    @ApiParam("班级ID") @RequestParam("clazzId")Long clazzId,
                                    @ApiParam("关键词") @RequestParam("keyword")String keyword,
                                    @ApiParam("查询条件") @RequestParam("condit")String condit,
                                    @ApiParam("当前页") @RequestParam("currentPage")Integer currentPage,
                                    @ApiParam("条数") @RequestParam("pageSize")Integer pageSize){

        //条件构造器
        QueryWrapper<VeDictYears> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("curYear",1);

        VeDictYears one = veDictYearsService.getOne(queryWrapper);

        if(one == null){
            return Result.error("列表加载失败：当前年份未启用！");
        }

        //获取当前年份
        String curYear = one.getCode();

        if(facultyId == 0){
            facultyId = null;
        }
        if(specialtyId == 0){
            specialtyId = null;
        }
        if(clazzId == 0){
            clazzId = null;
        }

        //页码条件
        Integer current = (currentPage-1)*pageSize;
        //获取集合
       List<VeZsRegistrationVo> list = veZsRegistrationService.getStuInfoList(curYear, isNum,facultyId, specialtyId, clazzId, keyword, condit, current, pageSize);
        //        ---------------林彬辉(获取学号和年级名称）
//        BasicResponseBO<List<VeBaseGrade>> listBasicResponseBO = iVeBaseManageService.getGradeAll();
//        List<VeBaseGrade> gradeList = listBasicResponseBO.getResult();
        List<VeBaseGrade> gradeList = veBaseGradeService.list();//2021.9.2
        for (VeZsRegistrationVo v : list){
            //获取班级信息
//            BasicResponseBO<VeBaseBanji> baseBanjiBasicResponseBO = iVeBaseManageService.getBanjiById(v.getClassId());
//            VeBaseBanji baseBanji = baseBanjiBasicResponseBO.getResult();

            VeBaseBanji baseBanji = veBaseBanjiService.getById(v.getClassId());//2021.9.2
            //添加班级名称
            if (baseBanji==null){
                v.setXzbmc("未查到班级名称");
                v.setTea("查无班主任信息");
            }else {
                v.setXzbmc(baseBanji.getXzbmc());
                //根据班主任id查教师信息，获取姓名
//                BasicResponseBO<VeBaseTeacher> baseTeacherBasicResponseBO = iVeBaseManageService.getTeaById(baseBanji.getBzrUserId());
//                BasicResponseBO<VeBaseTeacher> baseTeacherBasicResponseBO = iVeBaseManageService.getTeaByUserId(baseBanji.getBzrUserId());
//                VeBaseTeacher baseTeacher = baseTeacherBasicResponseBO.getResult();
                QueryWrapper<VeBaseTeacher> teacherQueryWrapper = new QueryWrapper<>();
                teacherQueryWrapper.eq("user_id",baseBanji.getBzrUserId());
                VeBaseTeacher baseTeacher = veBaseTeacherService.getOne(teacherQueryWrapper);//2021.9.2
                if (baseTeacher==null){
                    v.setTea("查无班主任信息");
                }else {
                    v.setTea(baseTeacher.getXm());
                }
            }



            // 获取学号
//            接口获取
//            BasicResponseBO<VeBaseStudent> baseStudentBasicResponseBO = iVeBaseManageService.getStudentById(v.getId());
//            BasicResponseBO<List<VeBaseStudent>> studentAll = iVeBaseManageService.getStudentAll();
//            List<VeBaseStudent> students = studentAll.getResult();
            List<VeBaseStudent> students = veBaseStudentService.list();//2021.9.2
            for (VeBaseStudent student : students){
                if (v.getSfzh().equals(student.getSfzh())){
//                if (v.getId() == student.getId()){
                    v.setXh(student.getXh());

                    v.setXsdqztm(student.getXsdqztm());
                    break;
                }
            }
            if (v.getXh()==null){
                v.setXh("查无学号");
            }
            if (v.getXsdqztm()==null){
                v.setXsdqztm("查无当前状态");
            }
//            VeBaseStudent student = baseStudentBasicResponseBO.getResult();
//            本地数据库获取
//            QueryWrapper<VeBaseStudent> wrapper = new QueryWrapper<VeBaseStudent>().eq("SFZH", v.getSfzh());
//            VeBaseStudent student = veBaseStudentService.getOne(wrapper);
//            if (student != null){
//                v.setXh(student.getXh());
//            }else {
//                v.setXh("");
//            }
            //获取年级名称
            for (VeBaseGrade grade :gradeList){
                if (v.getGradeId() == grade.getId()){
                    v.setNjmc(grade.getNjmc());
                    break;
                }
            }

//            BasicResponseBO<VeBaseGrade> basicResponseBO = iVeBaseManageService.getGradeById()
        }
        //条件构造器
        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
        wrapper.eq("isCheck",1);
        wrapper.eq("isAdmit",1);
        wrapper.eq("isReport",1);
//        --------------------林彬辉，添加判断是否显示已有学号的学生
            wrapper.eq("isNum",isNum);
//        --------------------------
//        wrapper.eq("isNum",0);
        wrapper.eq("RXNF",curYear);
        wrapper.isNotNull("classId");

        if(clazzId != null){
            wrapper.eq("classId",clazzId);
        }

        if(facultyId != null){
            wrapper.eq("falId",facultyId);
        }

        if(specialtyId != null){
            wrapper.eq("specId",specialtyId);
        }

        if(condit != null && keyword != null && (!keyword.trim().equals(""))){
            wrapper.like(condit,keyword);
        }

        //查询总数
        Integer count = veZsRegistrationService.list(wrapper).size();

        HashMap<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("count",count);

        return Result.OK(map);

    }


    /**
     * 导出
     * @return 导出表格流
     */
    @AutoLog(value = "新生信息excel表格")
    @ApiOperation(value = "新生信息excel表格", notes = "新生信息—导出excel表格")
    @GetMapping(value = "/exportTable")
//    @ApiParam("专业部ID") @RequestParam("facultyId")Long facultyId,
//    @ApiParam("是否拥有学号") @RequestParam("isNum")Integer isNum,
//    @ApiParam("专业ID") @RequestParam("specialtyId")Long specialtyId,
//    @ApiParam("班级ID") @RequestParam("clazzId")Long clazzId,
//    @ApiParam("关键词") @RequestParam("keyword")String keyword,
//    @ApiParam("查询条件") @RequestParam("condit")String condit,
    public ModelAndView exportTable(@ApiParam("查询条件") @RequestParam("conditions") String conditions) {
        //        ------------林彬辉
        Map<String ,Object> conditionsMap = JSONObject.parseObject(conditions);
        Long facultyId = Long.parseLong(conditionsMap.get("facultyId").toString());
        Long specialtyId = Long.parseLong(conditionsMap.get("specialtyId").toString());
        Long clazzId = Long.parseLong(conditionsMap.get("clazzId").toString());
        Integer isNum = Integer.parseInt(conditionsMap.get("isNum").toString());
        String keyword = conditionsMap.get("keyword").toString();
        String condit = conditionsMap.get("condit").toString();
        // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 查数据获得 表格的集合
        List<ExportStuInfoVo> list = veZsRegistrationService.exportStuInfo(isNum,facultyId,specialtyId,clazzId,keyword,condit);
        //        ---------------林彬辉(获取学号和年级名称）
//        BasicResponseBO<List<VeBaseGrade>> listBasicResponseBO = iVeBaseManageService.getGradeAll();
//        List<VeBaseGrade> gradeList = listBasicResponseBO.getResult();
        List<VeBaseGrade> gradeList = veBaseGradeService.list();//2021.9.2

        for (ExportStuInfoVo v : list) {
            //获取班级信息
//            BasicResponseBO<VeBaseBanji> baseBanjiBasicResponseBO = iVeBaseManageService.getBanjiById(v.getClassId());
//            VeBaseBanji baseBanji = baseBanjiBasicResponseBO.getResult();
            VeBaseBanji baseBanji = veBaseBanjiService.getById(v.getClassId());//2021.9.2
            //添加班级名称
            if (baseBanji == null) {
                v.setXzbmc("未查到班级名称");
//                v.setTea("查无班主任信息");
            } else {
                v.setXzbmc(baseBanji.getXzbmc());

            }

            // 获取学号
//            接口获取
//            BasicResponseBO<VeBaseStudent> baseStudentBasicResponseBO = iVeBaseManageService.getStudentById(v.getId());
//            BasicResponseBO<List<VeBaseStudent>> studentAll = iVeBaseManageService.getStudentAll();
//            List<VeBaseStudent> students = studentAll.getResult();
            List<VeBaseStudent> students = veBaseStudentService.list();
            for (VeBaseStudent student : students) {
                if (v.getSfzh().equals(student.getSfzh())){
//                if (v.getId() == student.getId()) {
                    v.setXh(student.getXh());

                    v.setXszt(student.getXsdqztm());
                    break;
                }
            }
            if (v.getXh() == null) {
                v.setXh("查无学号");
            }
            if (v.getXszt() == null) {
                v.setXszt("查无当前状态");
            }
//            VeBaseStudent student = baseStudentBasicResponseBO.getResult();
//            本地数据库获取
//            QueryWrapper<VeBaseStudent> wrapper = new QueryWrapper<VeBaseStudent>().eq("SFZH", v.getSfzh());
//            VeBaseStudent student = veBaseStudentService.getOne(wrapper);
//            if (student != null){
//                v.setXh(student.getXh());
//            }else {
//                v.setXh("");
//            }
            //获取年级名称
            for (VeBaseGrade grade : gradeList) {
                if (v.getGradeId() == grade.getId()) {
                    v.setNjmc(grade.getNjmc());
                    break;
                }
            }
        }
            for (ExportStuInfoVo vo : list) {
                //数据加工处理
                String sex = vo.getXbm().equals("1") ? "男" : "女";
                vo.setXbm(sex);
            }

        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "新生信息");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, ExportStuInfoVo.class);

        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1:title:表格标题, 参数2:secondTitle:第二行的标题, 参数3:sheetName:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("新生信息", "导出人:" + user.getRealname(), "新生信息列表");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    /**
     * 导出excel模板
     * @return 导出表格流
     */
    @AutoLog(value = "新生信息excel表格")
    @ApiOperation(value = "新生信息excel表格", notes = "新生信息—导出excel模板")
    @GetMapping(value = "/exportModel")
    public ModelAndView exportModel() {

        // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());

        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "新生信息");
        mv.addObject(NormalExcelConstants.CLASS, VeZsRegistrationVo.class);

        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // ExportParams  Export工具类   （参数1:title:表格标题, 参数2:secondTitle:第二行的标题, 参数3:sheetName:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("新生信息", "导出人:" + user.getRealname(), "新生信息记录");

        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<VeZsRegistrationVo>());
        return mv;
    }

    @ApiOperation(value="获取新生信息")
    @PostMapping(value = "/getInfoByID")
    public Result<?> getInfoByID(@ApiParam("id") @RequestParam("id") Long id ) {
        VeZsRegistrationVo printStuInfo = veZsRegistrationService.getPrintStuInfo(id);
//        BasicResponseBO<VeBaseBanji> banjiBasicResponseBO = iVeBaseManageService.getBanjiById(printStuInfo.getClassId());
//        VeBaseBanji veBaseBanji = banjiBasicResponseBO.getResult();
        VeBaseBanji veBaseBanji = veBaseBanjiService.getById(printStuInfo.getClassId());//2021.9.2
        if (veBaseBanji == null){
            printStuInfo.setTea("未查到教师信息");
        }else {
//            BasicResponseBO<VeBaseTeacher> teacherBasicResponseBO = iVeBaseManageService.getTeaByUserId(veBaseBanji.getBzrUserId());
            QueryWrapper<VeBaseTeacher> teacherQueryWrapper = new QueryWrapper<>();
            teacherQueryWrapper.eq("user_id",veBaseBanji.getBzrUserId());
            VeBaseTeacher baseTeacher = veBaseTeacherService.getOne(teacherQueryWrapper);
            BasicResponseBO<VeBaseTeacher> teacherBasicResponseBO =new BasicResponseBO<>();
            teacherBasicResponseBO.setResult(baseTeacher);//2021.9.2
            if (teacherBasicResponseBO.getResult() == null){
                printStuInfo.setTea("未查到教师信息");
            }else {
                printStuInfo.setTea(teacherBasicResponseBO.getResult().getXm());
            }

        }

        System.out.println(printStuInfo);
        return Result.OK(printStuInfo);
    }

}
